<template>
    <div class="comp11 boxss">
        <div class="titles">
            库存分布图
            <el-button 
                type="text" 
                icon="el-icon-refresh" 
                @click="refreshData"
                :loading="loading"
                style="margin-left: 10px; font-size: 14px;"
                title="刷新数据">
            </el-button>
        </div>

        <div class="chart-container" v-loading="loading" v-if="checkPermi(['home:Inventory:statistics'])">
            <!-- 环形图容器 -->
            <div id="inventoryChart" class="chart-box"></div>

            <!-- 分页控制 - 当游戏太多时显示 -->
            <div class="pagination-control" v-if="totalPages > 1">
                <div class="page-info">{{ currentPage }}/{{ totalPages }}</div>
                <div class="page-buttons">
                    <button
                        class="page-btn prev"
                        @click="prevPage"
                        :disabled="currentPage === 1">
                        ‹
                    </button>
                    <button
                        class="page-btn next"
                        @click="nextPage"
                        :disabled="currentPage === totalPages">
                        ›
                    </button>
                </div>
            </div>

            <!-- 无数据提示 -->
            <div v-if="!loading && allGameData.length === 0" class="no-data">
                <i class="el-icon-box"></i>
                <p>暂无库存数据</p>
            </div>
        </div>
        <el-empty v-else :image-size="100" description="您还没有该模块权限,请联系管理员分配权限!"></el-empty>
    </div>
</template>
<script>
import homeApi from "@/api/home/newIndex";
import * as echarts from "echarts";
import EleResize from '@/utils/esresize';
export default {
    name: 'Comp11',
    data() {
        return {
            myChart: null,
            totalInventory: 0, // 库存总量
            currentPage: 1, // 当前页
            itemsPerPage: 20, // 每页显示的游戏数量
            allGameData: [],
            loading: false,
            // 预定义颜色数组
            colorPalette: [
                '#6C5DD3', '#7FBA7A', '#FFE100', '#FF6B9D', '#36CFC9',
                '#FAAD14', '#F759AB', '#40A9FF', '#73D13D', '#FF7A45',
                '#BFBFBF', '#FF4D4F', '#52C41A', '#1890FF', '#722ED1'
            ]
        }
    },
    computed: {
        // 总页数
        totalPages() {
            return Math.ceil(this.allGameData.length / this.itemsPerPage);
        },
        // 当前页显示的游戏数据
        gameData() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            const end = start + this.itemsPerPage;
            return this.allGameData.slice(start, end);
        },
        // 计算百分比
        gameDataWithPercent() {
            return this.gameData.map(item => ({
                ...item,
                percent: ((item.value / this.actualTotalInventory) * 100).toFixed(1)
            }));
        },
        // 计算实际总库存量
        actualTotalInventory() {
            return this.allGameData.reduce((sum, item) => sum + item.value, 0);
        }
    },
    watch: {
        // 监听游戏数据变化，确保图表及时更新
        gameData: {
            handler(newVal) {
                // console.log('gameData watch触发:', newVal);
                if (this.myChart && this.gameData.length > 0) {
                    this.setChartOption();
                } 
            },
            immediate: true
        }
    },
    mounted() {
        // 延迟初始化，确保数据完全准备好
        this.$nextTick(() => {
            setTimeout(() => {
                this.initChart();
                this.fetchInventoryData();
            }, 100);
        });
    },
    beforeDestroy() {
        if (this.myChart) {
            this.myChart.dispose();
        }
    },
    methods: {
        initChart() {
            const chartDom = document.getElementById('inventoryChart');
            if (!chartDom) {
                return;
            }

            this.myChart = echarts.init(chartDom);
               var resizeDiv = document.getElementById('inventoryChart')
            EleResize.on(resizeDiv, () => {
                this.myChart.resize()
            })
        },
        setChartOption() {
            if (!this.myChart) {
                return;
            }

            // 准备图表数据
            const chartData = this.gameData.filter(item => !item.disabled).map(item => ({
                value: item.value,
                name: item.name,
                itemStyle: {
                    color: item.color
                }
            }));
            if (chartData.length === 0) {
                return;
            }

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return `${params.seriesName}<br/>${params.name}: ${params.value}个 (${params.percent}%)`;
                    }
                },
                legend: {
                    show: false
                },
                series: [
                    {
                        name: '库存分布',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        center: ['50%', '50%'],
                        data: chartData,
                        label: {
                            show: true,
                            position: 'outside',
                            formatter: function(params) {
                                return `${params.name}: ${params.value}个`;
                            }
                        },
                        labelLine: {
                            show: true
                        }
                    }
                ],
                graphic: [
                    {
                        type: 'text',
                        left: 'center',
                        top: '45%',
                        style: {
                            text: '库存总量',
                            textAlign: 'center',
                            fill: '#666',
                            fontSize: 14
                        }
                    },
                    {
                        type: 'text',
                        left: 'center',
                        top: '55%',
                        style: {
                            text: this.actualTotalInventory > 0 ? this.actualTotalInventory.toString() : '0',
                            textAlign: 'center',
                            fill: '#333',
                            fontSize: 24,
                            fontWeight: 'bold'
                        }
                    }
                ]
            };

          
            this.myChart.setOption(option, true); // 第二个参数true表示不合并，完全替换
            
        },
        // 切换游戏显示/隐藏
        toggleGame(index) {
            // 计算在allGameData中的实际索引
            const actualIndex = (this.currentPage - 1) * this.itemsPerPage + index;
            this.allGameData[actualIndex].disabled = !this.allGameData[actualIndex].disabled;
            this.setChartOption();
        },
        // 上一页
        prevPage() {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.setChartOption();
            }
        },
        // 下一页
        nextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
                this.setChartOption();
            }
        },
        // 获取库存数据
        async fetchInventoryData() {
            try {
                this.loading = true;
                // 调用API获取数据
                const response = await homeApi.huantype();
                
                if (response && response.code === 200 && response.data) {
                    this.processApiData(response.data);
                } else {
                    console.warn('获取库存数据失败:', response);
                    this.$message.warning('获取库存数据失败');
                    this.setDefaultData();
                }
            } catch (error) {
                console.error('获取库存数据错误:', error);
                // 只在网络错误或服务器错误时显示错误消息
                if (error.code !== 'ECONNABORTED' && error.response?.status !== 404) {
                    this.$message.error('网络连接失败，请检查网络连接');
                }
                this.setDefaultData();
            } finally {
                this.loading = false;
            }
        },
        // 处理API返回的数据
        processApiData(data) {
            const { total = 0, rows = [] } = data;
            this.totalInventory = total;
            
            // 验证数据格式
            if (!Array.isArray(rows) || rows.length === 0) {
                this.setDefaultData();
                return;
            }
            
            // 转换API数据格式
            this.allGameData = rows.map((item, index) => {
                // 验证必需字段
                if (!item || typeof item.gameId === 'undefined' || !item.gameName || typeof item.count === 'undefined') {
                    console.warn('无效的游戏数据项:', item);
                    return null;
                }
                
                return {
                    gameId: item.gameId,
                    name: item.gameName,
                    value: Math.max(0, Number(item.count) || 0), // 确保数值为非负数
                    color: this.colorPalette[index % this.colorPalette.length],
                    disabled: false
                };
            }).filter(item => item !== null); // 移除无效数据
            
            // 如果没有有效数据，设置默认状态
            if (this.allGameData.length === 0) {
                this.setDefaultData();
                return;
            }
            
            // 数据处理完成后更新图表
            this.$nextTick(() => {
                if (this.myChart && this.gameData.length > 0) {
                    this.setChartOption();
                }
            });
        },
        // 设置默认数据（当API调用失败时使用）
        setDefaultData() {
            this.allGameData = [
                { gameId: 1, name: '暂无数据', value: 0, color: '#BFBFBF', disabled: false }
            ];
            this.totalInventory = 0;
        },
        // 刷新数据
        refreshData() {
            this.fetchInventoryData();
        }
    }
}
</script>
<style lang="scss" scoped>
@import url('./style.css');

.comp11 {
    position: relative;
}


.chart-container {
    margin-top: 16px;
}

.chart-box {
    width: 100%;
    height: 280px;
}
.pagination-control {
    position: absolute;
   top : 0px;
    right: 0px;
    display: flex;
    align-items: center;
    gap: 10px;
    background: rgba(255, 255, 255, 0.9);
    padding: 8px 12px;
    border-radius: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .page-info {
        font-size: 12px;
        color: #666;
        font-weight: 500;
    }

    .page-buttons {
        display: flex;
        gap: 4px;
    }

    .page-btn {
        width: 24px;
        height: 24px;
        border: 1px solid #d9d9d9;
        background: #fff;
        border-radius: 50%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #666;
        transition: all 0.2s ease;

        &:hover:not(:disabled) {
            border-color: #6C5DD3;
            color: #6C5DD3;
        }

        &:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }
    }
}

// 移除游戏列表样式，改用分页控制

.no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #999;
    
    i {
        font-size: 48px;
        margin-bottom: 12px;
        opacity: 0.5;
    }
    
    p {
        margin: 0;
        font-size: 14px;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .chart-box {
        height: 280px;
    }

    .pagination-control {
        bottom: 5px;
        right: 10px;
        padding: 6px 10px;

        .page-info {
            font-size: 11px;
        }

        .page-btn {
            width: 20px;
            height: 20px;
            font-size: 12px;
        }
    }
}
</style>